import os

import aiosqlite

from config.database import AsyncSessionLocal
from config.env import KylinConfig
from module_kylin.dao.trade_dao import TradeDao
from module_kylin.entity.do.trade_do import KylinTrade


async def job():  # 修改函数定义
    """
    定时任务执行异步函数示例
    """
    kylin_file_path = KylinConfig.get('KYLIN_FILE_PATH', '')
    print(kylin_file_path)

    # 遍历目录改为异步处理
    for root, dirs, files in await asyncio.to_thread(os.walk, kylin_file_path, topdown=True, onerror=None,
                                                     followlinks=False):
        for file in files:
            if file.endswith('.db'):
                file_path = os.path.join(root, file)
                try:
                    # 使用异步SQLite连接
                    async with aiosqlite.connect(str(file_path)) as conn:
                        cursor = await conn.cursor()
                        await cursor.execute('SELECT * FROM trade')
                        rows = await cursor.fetchall()
                        # print(f"文件: {file_path}")
                        # 异步打印处理
                        # [await asyncio.to_thread(print, row) for row in rows]

                        # 异步数据库会话
                        async with AsyncSessionLocal() as mysql_session:
                            try:
                                # 批量插入优化
                                mysql_session.add_all(
                                    KylinTrade(name=row[1], trade_id=row[0], date=row[2], time=row[3],
                                               price=row[4], direction=row[5], offset=row[6], volume=row[7], pos=row[8])
                                    for row in rows
                                )
                                await mysql_session.commit()
                                print(f"文件: {file_path},成功插入{len(rows)}条记录到MySQL")
                            except Exception as e:
                                await mysql_session.rollback()
                                print(f"文件: {file_path},数据库插入失败: {str(e)}")

                except Exception as e:
                    print(f"处理文件 {file_path} 时出错: {e}")


async def read_trade_from_config_db():
    """
    从配置的数据库读取trade表数据并输出
    """
    print('开始读取数据库交易记录...')
    async with AsyncSessionLocal() as session:
        trades = await TradeDao.get_trade_all(session)
        for trade in trades:
            print(f"交易记录: {trade.name}")
    print('数据库读取完成')


if __name__ == '__main__':
    import asyncio

    # get_mysql_trade()
    asyncio.run(job())
